package comptadub

class ParametreController {
    
	static allowedMethods = [update: "POST"]

    def index = {
        redirect(action: "list", params: params)
    }

    def list = {		
        params.max = Math.min(params.max ? params.int('max') : 10, 100)
        [parametreInstanceList: Parametre.list(params), parametreInstanceTotal: Parametre.count()]
    }

    def edit = {
        def parametreInstance = Parametre.get(params.id)
        if (!parametreInstance) {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'parametre.label', default: 'Parametre'), params.id])}"
            redirect(action: "list")
        }
        else {
            return [parametreInstance: parametreInstance]
        }
    }

    def update = {
        def parametreInstance = Parametre.get(params.id)
        if (parametreInstance) {
            if (params.version) {
                def version = params.version.toLong()
                if (parametreInstance.version > version) {
                    
                    parametreInstance.errors.rejectValue("version", "default.optimistic.locking.failure", [message(code: 'parametre.label', default: 'Parametre')] as Object[], "Another user has updated this Parametre while you were editing")
                    render(view: "edit", model: [parametreInstance: parametreInstance])
                    return
                }
            }
            parametreInstance.properties = params
            if (!parametreInstance.hasErrors() && parametreInstance.save(flush: true)) {
                flash.message = "${message(code: 'default.updated.message', args: [message(code: 'parametre.label', default: 'Parametre'), parametreInstance.id])}"

                /* redémarage des jobs avec les nouveaux paramêtres 
                if (parametreInstance.nom == "mail_cron_expression") {
                    EnvoiMailJob.schedule(parametreInstance.valeur)
                    flash.message = "Job mail rebooté avec " + parametreInstance.valeur
                }
                if (parametreInstance.nom == "loyer_cron_expression") {
                    LoyerMensuelJob.schedule(parametreInstance.valeur)
                    flash.message = "Job loyer rebooté avec " + parametreInstance.valeur
                }*/
                
                redirect(action: "list")
            }
            else {
                render(view: "edit", model: [parametreInstance: parametreInstance])
            }
        }
        else {
            flash.message = "${message(code: 'default.not.found.message', args: [message(code: 'parametre.label', default: 'Parametre'), params.id])}"
            redirect(action: "list")
        }
    }
}
